package com.zzyl.nursing.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.nursing.domain.Contract;
import com.zzyl.nursing.domain.HealthAssessment;
import com.zzyl.nursing.service.IContractService;
import com.zzyl.nursing.service.IHealthAssessmentService;
import com.zzyl.oss.client.OSSAliyunFileStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author 东辰末末
 */
@Slf4j
@Component("oSSTask")
public class OSSTask {
    @Autowired
    private OSSAliyunFileStorageService aliyunFileStorageService;
    @Autowired
    private IHealthAssessmentService healthAssessmentService;

    // 定义一个方法ossFileCheck，用于检查OSS上的文件
    public void ossFileCheck() {
        log.info("执行OSS文件清理");
        Map<String, Long> fileMap = aliyunFileStorageService.dataList();
        if (fileMap.isEmpty()) {
            return;
        }
        List<HealthAssessment> healthAssessments = healthAssessmentService.list();
        if (healthAssessments == null || healthAssessments.isEmpty()) {
            for (Map.Entry<String, Long> entry : fileMap.entrySet()) {
                aliyunFileStorageService.delete(entry.getKey());
            }
            return;
        }

        Set<Map.Entry<String, Long>> fileInfo = fileMap.entrySet();
        for (Map.Entry<String, Long> entry : fileInfo) {
            if (shouldDeleteFile(entry.getKey(), healthAssessments)) {
                aliyunFileStorageService.delete(entry.getKey());
            }
        }
    }


    /**
     * 判断是否应该删除文件。
     * 该方法通过检查健康评估列表中每个评估的物理报告URL是否包含或等于给定的文件路径来确定是否应该删除文件。
     * @param filePath 需要检查的文件路径，类型为String。
     * @param healthAssessments 健康评估列表，列表中的元素为HealthAssessment类型。
     * @return 如果健康评估列表中有任何物理报告URL包含或等于给定的文件路径，则返回false，表示不应该删除文件；否则返回true，表示应该删除文件。
     */
    private boolean shouldDeleteFile(String filePath, List<HealthAssessment> healthAssessments) {
        for (HealthAssessment healthAssessment : healthAssessments) {
            String url = healthAssessment.getPhysicalReportUrl();
            if (url.contains(filePath) || url.equals(filePath)) {
                return false;
            }
        }
        return true;
    }
}

